/*
 * To change this license header, choose License Headers in Project Properties. To change this
 * template file, choose Tools | Templates and open the template in the editor.
 */

package com.gitee.jmash.websocket.model;

import java.io.StringReader;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.gitee.jmash.common.security.JmashPrincipal;
import com.gitee.jmash.core.utils.JsonbUtil;
import com.gitee.jmash.websocket.util.TokenUtil;
import jakarta.json.Json;
import jakarta.json.JsonReader;
import jakarta.websocket.DecodeException;
import jakarta.websocket.Decoder;
import jakarta.websocket.EndpointConfig;

/**
 * Message Decoder.
 *
 * @author Juneau
 */
public class MessageDecoder implements Decoder.Text<Message> {

  private static Log log = LogFactory.getLog(MessageDecoder.class);

  @Override
  public Message decode(String jsonMessage) throws DecodeException {
    Message message = JsonbUtil.fromJson(jsonMessage, Message.class);
    if (MsgType.subscribe.equals(message.getMsgType())
        || MsgType.unsubscribe.equals(message.getMsgType())) {
      SubscribeMessage msg = JsonbUtil.fromJson(jsonMessage, SubscribeMessage.class);
      if (StringUtils.isNotBlank(msg.getToken())) {
        JmashPrincipal principal = TokenUtil.parseJwt(msg.getToken());
        msg.setPrincipal(principal);
      }
      return msg;
    }
    return message;
  }

  @Override
  public boolean willDecode(String jsonMessage) {
    try (JsonReader reader = Json.createReader(new StringReader(jsonMessage))) {
      // Check if incoming message is valid JSON
      reader.readObject();
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  @Override
  public void init(EndpointConfig ec) {
    log.info("Initializing message decoder");
  }

  @Override
  public void destroy() {
    log.info("Destroyed message decoder");
  }

}
